//
//  StatusPictureView.swift
//  Weibo10
//
//  Created by male on 15/10/20.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SDWebImage
/// 照片之间的间距
private let StatusPictureViewItemMargin: CGFloat = 8
/// 可重用表示符号
private let StatusPictureCellId = "StatusPictureCellId"
/// 配图视图
class StatusPictureView: UICollectionView {
    /// 微博视图模型
    var viewModel: StatusViewModel? {
        didSet {
            // 自动计算大小
            sizeToFit()
            
            // 刷新数据 － 如果不刷新，后续的 collectionView 一旦被复用，不再调用数据源方法
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }
    

    // MARK: - 构造函数
    init() {
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = StatusPictureViewItemMargin
        layout.minimumLineSpacing = StatusPictureViewItemMargin
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        dataSource = self
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureCellId)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
// MARK: - 计算视图大小
extension StatusPictureView {
    
    /// 计算视图大小
    private func calcViewSize() -> CGSize {
        
        // 1. 准备
        // 每行的照片数量
        let rowCount: CGFloat = 3
        // 最大宽度
        let maxWidth = UIScreen.mainScreen().bounds.width - 2 * StatusCellMargin
        let itemWidth = (maxWidth - 2 * StatusPictureViewItemMargin) / rowCount
        
        // 2. 设置 layout 的 itemSize
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        // 3. 获取图片数量
        let count = viewModel?.thumbnailUrls?.count ?? 0
        
        // 计算开始
        // 1> 没有图片
        if count == 0 {
            return CGSizeZero
        }
        
        // 2> 一张图片
        if count == 1 {
            var size = CGSize(width: 150, height: 120)

            if let key = viewModel?.thumbnailUrls?.first?.absoluteString {
                
                let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
                size = image.size
            }
            // 过窄处理 - 针对长图
            size.width = size.width < 40 ? 40 : size.width
            // 过宽的图片
            if size.width > 300 {
                let w: CGFloat = 300
                let h = size.height * w / size.width
                
                size = CGSize(width: w, height: h)
            }
            // 内部图片的大小
            layout.itemSize = size
            
            // 配图视图的大小
            return size
        }
        
        // 3> 四张图片 2 * 2 的大小
        if count == 4 {
            let w = 2 * itemWidth + StatusPictureViewItemMargin
            
            return CGSize(width: w, height: w)
        }
        
        // 4> 其他图片 按照九宫格来显示
        // 计算出行数
        /**
        2 3
        5 6
        7 8 9
        */
        let row = CGFloat((count - 1) / Int(rowCount) + 1)
        let h = row * itemWidth + (row - 1) * StatusPictureViewItemMargin
        let w = rowCount * itemWidth + (rowCount - 1) * StatusPictureViewItemMargin
        
        return CGSize(width: w, height: h)
    }
}
// MARK: - UICollectionViewDataSource
extension StatusPictureView: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return viewModel?.thumbnailUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureCellId, forIndexPath: indexPath) as! StatusPictureViewCell
        
        cell.imageURL = viewModel!.thumbnailUrls![indexPath.item]
        
        return cell
    }
}
private class StatusPictureViewCell:UICollectionViewCell{
    var imageURL:NSURL?{
        didSet{
            imageView.sd_setImageWithURL(imageURL,
                placeholderImage: nil,                      // 在调用 OC 的框架时，可/必选项不严格
                options: [SDWebImageOptions.RetryFailed,    // SD 超时时长 15s，一旦超时会记入黑名单
                    SDWebImageOptions.RefreshCached])
            
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI(){
        contentView.addSubview(imageView)
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    private lazy var imageView:UIImageView = {
            let v = UIImageView()
            v.contentMode = UIViewContentMode.ScaleAspectFill
            v.clipsToBounds = true
            return v
        }()

}
